<template>
  <div class="last-tables">
    <Tables
      :tableData="sortList"
      :tableLabel="tableLabel"
      :handleSelectionChange="handleSelectionChange"
      :handleUpdate="handleUpdate"
      :handleDelete="handleDeleted"
      :handleFieldEvent="handleFieldEvent"
    />
    <el-dialog
      title="表字段"
      :visible.sync="tableFieldDialog"
      width="65%"
      :close-on-click-modal="false"
      >
      <div>
        <div>
          <el-form class="dialog-form" ref="form" :model="form" label-width="80px">
            <el-form-item class="input-width" label="字段名称">
              <el-input  v-model="form.fieldName" placeHolder="请输入名称"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button size="mini" type="primary" icon="el-icon-search" @click="onSubmit">搜索</el-button>
              <el-button size="mini" icon="el-icon-refresh" @click="onReset()">重置</el-button>
            </el-form-item>
          </el-form>
          <el-row :gutter="10" class="btn-wrap">
            <el-col :span="1.5">
              <el-button
                type="primary"
                icon="el-icon-plus"
                size="mini"
                plain
                @click="addTableFieldVal(false,rowsTotal)"
              >新增</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="success"
                icon="el-icon-edit"
                size="mini"
                plain
                :disabled="single"
                @click="editTableField('',true)"
              >修改</el-button>
            </el-col>
            <el-col :span="1.5">
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                plain
                :disabled="multiple"
                @click="handleDelTableField"
              >删除</el-button>
            </el-col>
          </el-row>
          <el-table
            stripe
            :data="TableFieldList"
            style="width: 100%"
            @selection-change="handleCheckSelection"
          >
            <el-table-column
              align="center"
              type="selection"
              width="55">
            </el-table-column>
            <el-table-column
              prop="fieldName"
              label="字段名称"
              show-overflow-tooltip
              >
            </el-table-column>
            <el-table-column
              prop="fieldAlias"
              label="字段别名"
              show-overflow-tooltip
              >
            </el-table-column>
            <el-table-column
              prop="fieldType"
              show-overflow-tooltip
              label="字段类型">
              <template slot-scope="scope">
                {{scope.row.fieldType | formatFieldType}}
              </template>
            </el-table-column>
            <el-table-column
              prop="fieldLength"
              align="right"
              show-overflow-tooltip
              label="字段长度">
            </el-table-column>
            <el-table-column
              align="center"
              prop="isList"
              show-overflow-tooltip
              label="列表显示">
              <template slot-scope="scope">
                {{scope.row.isList === '0' ? '是' : '否'}}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="isTitle"
              show-overflow-tooltip
              label="是否标题">
              <template slot-scope="scope">
                {{scope.row.isTitle === '0' ? '是' : '否'}}
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              width="200px"
              label="操作">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-edit"
                  @click="editTableField(scope.row,true)"
                >修改</el-button>
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="handleDelTableField(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
      <el-button type="primary" @click="tableFieldDialog = false">确 定</el-button>
      <el-button @click="tableFieldDialog = false">取 消</el-button>

  </span>
    </el-dialog>

    <el-dialog
      title="表字段"
      :visible.sync="FieldInfoOpen"
      width="700px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form ref="fieldForm" :model="fieldForm" :rules="fieldFormRules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="字段名称" prop="fieldName">
              <el-input v-model="fieldForm.fieldName" placeholder="请输入字段名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="字段别名" prop="fieldAlias">
              <el-input v-model="fieldForm.fieldAlias" placeholder="请输入字段别名" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="字段长度" prop="fieldLength">
              <el-input v-model="fieldForm.fieldLength" placeholder="请输入字段长度" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="默认值" prop="fieldDefaultValue">
              <el-input v-model="fieldForm.fieldDefaultValue" placeholder="请输入默认值" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="顺序号" prop="orderNo">
              <el-input v-model="fieldForm.orderNo" placeholder="请输入顺序号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="字段类型" prop="fieldType">
              <el-select v-model="fieldForm.fieldType" placeholder="请选择字段类型">
                <el-option
                  v-for="dict in fieldTypeOptions"
                  :key="dict.dictValue"
                  :label="dict.dictLabel"
                  :value="dict.dictValue"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="输入方式" prop="fieldInputType">
              <el-radio-group v-model="fieldForm.fieldInputType" @change="fieldTypeChange">
                <el-radio label="0">普通</el-radio>
                <el-radio label="1">字典选择</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col  :span="12">
            <el-form-item class="field-type-wrap" label="字典类型" prop="fieldDicType">
              <el-select :disabled="fieldForm.fieldInputType === '0'" v-model="fieldForm.fieldDicType" placeholder="请选择字典类型">
                <el-option
                  v-for="(dict,index) in dictList"
                  :key="index"
                  :label="dict.dictName"
                  :value="dict.dictType"
                />
              </el-select>
              <div class="field-type-tips" v-if="fieldForm.fieldInputType === '1' && fieldForm.fieldDicType.length === 0" >请选择字典类型</div>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="可为空值" prop="isNull">
              <el-radio-group v-model="fieldForm.isNull">
                <el-radio label="0">是</el-radio>
                <el-radio label="1">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否标题" prop="isTitle">
              <el-radio-group v-model="fieldForm.isTitle">
                <el-radio label="0">是</el-radio>
                <el-radio label="1">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="列表展示" prop="isList">
              <el-radio-group v-model="fieldForm.isList">
                <el-radio label="0">是</el-radio>
                <el-radio label="1">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="可被查询" prop="isQuery">
              <el-radio-group v-model="fieldForm.isQuery">
                <el-radio label="0">是</el-radio>
                <el-radio label="1">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="可被编辑" prop="isEdit">
              <el-radio-group v-model="fieldForm.isEdit">
                <el-radio label="0">是</el-radio>
                <el-radio label="1">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否加密" prop="isEncrypt">
              <el-radio-group v-model="fieldForm.isEncrypt">
                <el-radio label="0">是</el-radio>
                <el-radio label="1">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否主键" prop="isPk">
              <el-radio-group v-model="fieldForm.isPk">
                <el-radio label="0">是</el-radio>
                <el-radio label="1">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="是否排序" prop="isSort">
              <el-radio-group v-model="fieldForm.isSort">
                <el-radio label="0">是</el-radio>
                <el-radio label="1">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="活动形式">
              <el-input type="textarea" v-model="fieldForm.desc"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAddField">确 定</el-button>
        <el-button @click="handleClose('fieldForm')">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getTableFieldList,
  addTableField,
  getTableFieldDetail,
  editTableFieldDetail,
  delTableField, getDictType
} from '@/api/system/sort'

import Tables from '@/components/Tables/index'

export default {
  name: 'lastTables',
  props:["sortList","handleSelectionChange","handleUpdate","handleDelete","tableLabel"],
  data(){
    return {
      tableFieldDialog:false, // 是否开启弹窗
      FieldInfoOpen:false,// 表字段详细信息弹窗
      form: {
        fieldName: ''
      },
      // 表字段列表
      TableFieldList: [],
      tableFieldRow:{},
      //  表字段详细信息
      fieldForm:{},
      // 表单验证
      fieldFormRules: {
        fieldName: [
          { required: true, message: "字段名称不能为空", trigger: "blur" },
          { pattern:'^[A-Za-z_]+$',message:"请输入英文和下划线",trigger:"blur"}
        ],
        fieldAlias: [
          { required: true, message: "字段别名不能为空", trigger: "blur" }
        ],
        fieldLength: [
          { required: true, message: "字段长度不能为空", trigger: "blur" }
        ],
        orderNo: [
          { required: true, message: "顺序号不能为空", trigger: "blur" },
          { pattern:'^\\d+$|^\\d+[.]?\\d+$',message: "请输入数字", trigger: "blur"}
        ],
        fieldType: [
          { required: true, message: "字段类型不能为空", trigger: "blur" }
        ],
        isPk: [
          { required: true, message: "是否主键不能为空", trigger: "blur" }
        ],
        isSort:[
          { required: true, message: "是否排序不能为空", trigger: "blur" }
        ],
        isNull: [
          { required: true, message: "是否可以为空不能为空", trigger: "blur" }
        ],
        isTitle: [
          { required: true, message: "是否标题不能为空", trigger: "blur" }
        ],
        isList: [
          { required: true, message: "是否列表展示不能为空", trigger: "blur" }
        ],
        isQuery: [
          { required: true, message: "是否可被查询不能为空", trigger: "blur" }
        ],
        isEdit: [
          { required: true, message: "是否可被编辑不能为空", trigger: "blur" }
        ],
        isEncrypt: [
          { required: true, message: "是否加密不能为空", trigger: "blur" }
        ],
        fieldInputType: [
          { required: true, message: "是否加密不能为空", trigger: "blur" }
        ],
        fieldDefaultValue: [
          { required: false, message: "默认值不能为空", trigger: "blur" }
        ]
      },
      // 字段类型选择
      fieldTypeOptions:[
        {
          dictValue:'int',
          dictLabel:'整型'
        },
        {
          dictValue:'varchar',
          dictLabel:'字符'
        },
        {
          dictValue:'text',
          dictLabel:'长文本'
        },
        {
          dictValue:'decimal',
          dictLabel:'浮点数'
        },
        {
          dictValue:'datetime',
          dictLabel:'日期'
        }
      ],
      isFieldEdit:false,
      ids:[],
      fNames:[],
      single: true,// 非单个禁用
      multiple: true,// 非多个禁用
      dictList:[],//字典类型
      onlyOneTitle:false,
      onlyOneRecNo:'',
      labels:["编号","分类名称","表名称","表别名","表类型","表状态"],
      rowsTotal: '0'
    }
  },
  components:{
    Tables
  },
  methods:{
    //多选
    handleSelection(selection){
      this.handleSelectionChange(selection)
    },
    //底层表修改
    handleUpdated(row){
      this.handleUpdate(row)
    },
    //底层表表字段
    handleFieldEvent(row){
      this.tableFieldRow = row
      this.getList(row)
      this.tableFieldDialog = true
    },
    async getList(row){
      this.form.recNo = row.recNo
      const res = await getTableFieldList(this.form)
      this.TableFieldList = res.rows
      this.rowsTotal=res.total
    },
    //底层表删除
    handleDeleted(row){
      this.handleDelete(row)
    },
    //表字段搜索
    onSubmit() {
      this.getList(this.tableFieldRow)
    },
    onReset(){
      this.form.fieldName = ""
      this.getList(this.tableFieldRow)
    },
     // 获取字典类型
    async getDict(){
      const res = await getDictType()
      this.dictList = res.data
    },
     // 重置表字段
    reset(){
      this.fieldForm = {
        fieldName:'',
        fieldAlias:'',
        fieldLength:'',
        orderNo:'',
        fieldDefaultValue:'',
        fieldType:'',
        fieldDicType:'',
        isPk:'1',
        isSort:'1',
        isNull:'0',
        isTitle:'1',
        isList:'0',
        isQuery:'0',
        isEdit:'0',
        isEncrypt:'1',
        fieldInputType:'0',
        desc:''
      }
    },
     // 添加表字段
     addTableField(val){
      this.reset()
       this.getDict()
      this.isFieldEdit = val
       this.onlyOneTitle = false
      this.FieldInfoOpen = true
    },

 //重置添加某些默认值
    resetVal(orderNo){
       this.fieldForm={
         orderNo: orderNo
       }
    },  
    // 添加表字段-方式2,传递默认值
  addTableFieldVal(val,val2){
      this.reset()
       this.getDict()
       this.resetVal(parseInt(val2)+1)
      this.isFieldEdit = val
       this.onlyOneTitle = false
      this.FieldInfoOpen = true
    },


    // 提交添加表字段
    submitAddField(){
      // console.log(this.TableFieldList)
      this.fieldForm.tableNo = this.TableFieldList[0].tableNo
      this.$refs.fieldForm.validate(async valid => {
        if(!valid){
          return
        }
        if(this.fieldForm.fieldInputType === "1" && !this.fieldForm.fieldDicType){
          return this.$message.error("请选择字典类型")
        }
        if(this.fieldForm.isTitle === '0' && this.fieldForm.isPk === '0'){
          return this.$message.error('主键和标题二者只能选其一')
        }
        this.TableFieldList.find(item => {
          if(item.isTitle === '0' && item.recNo !== this.onlyOneRecNo){
            this.onlyOneTitle = true
          }
        })
        if(this.fieldForm.isTitle === '0' && this.onlyOneTitle){
          return this.$message.error('每一张表只能有一个标题')
        }
        if(!this.isFieldEdit){
          const res = await addTableField(this.fieldForm)
          if(res.code === 200){
            this.$message.success(res.msg)
            this.FieldInfoOpen = false
            await this.getList(this.tableFieldRow)
          }else{
            this.$message.error(res.msg)
          }
        }else{
          const res = await editTableFieldDetail(this.fieldForm)
          if(res.code === 200){
            this.$message.success(res.msg)
            this.FieldInfoOpen = false
            await this.getList(this.tableFieldRow)
          }else{
            this.$message.error(res.msg)
          }
        }
      })
    },
    //  修改表字段
    async editTableField(row,val){
      // console.log(row.recNo)
      this.getDict()
      this.onlyOneRecNo = row.recNo
      this.onlyOneTitle = false
      this.FieldInfoOpen = true
      this.isFieldEdit = val
      const recNos = row.recNo || this.ids;
      const res = await getTableFieldDetail(recNos)
      this.fieldForm = res.data
      this.fieldForm.orderNo = res.data.orderNo.toString()
    },
  //  删除表字段
    async handleDelTableField(row){
      const recNos = row.recNo || this.ids;
      const fieldNames = row.fieldName || this.fNames
      this.$confirm('是否确认删除字段名称为"' + fieldNames + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(async () => {
        if(this.TableFieldList.length - this.fNames.length < 1 || this.TableFieldList.length ===1){
          return this.$message.error("至少保留一个字段")
        }
        await delTableField(recNos)
        await this.msgSuccess("删除成功");
        await this.getList(this.tableFieldRow)
      }).catch(err => {
        this.$message('取消删除');
      })
    },
    // 选中多选框
    handleCheckSelection(selection){
      // console.log(selection)
      this.ids = selection.map(item => item.recNo)
      this.fNames = selection.map(item => item.fieldName)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    // 输入方式切换
    fieldTypeChange(Radio){
      if(Radio === '0'){
        this.fieldForm.fieldDicType = ''
      }
    },
    handleClose(form) {
      this.$refs[form].resetFields();
      this.FieldInfoOpen = false;
    }
  },
  filters:{
    formatFieldType(val){
      switch(val){
        case "int" :
          return "整型"
          break
        case "varchar" :
          return "字符"
          break
        case "text" :
          return "长文本"
          break
        case "decimal" :
          return "浮点数"
          break
        case "datetime" :
          return "日期"
          break
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.last-tables{
  .dialog-form{
    display: flex;
    justify-content: space-between;
    .input-width{
      width: 300px!important;
    }
  }
  .btn-wrap{
    margin-bottom: 20px;
  }
  .pagination{
    display: flex;
    justify-content: flex-end;
    margin-top: 10px;
  }
}
::v-deep .el-table{
  max-height: 540px;
  overflow: auto;
}
.field-type-wrap{
  position: relative;
  .field-type-tips{
    position: absolute;
    top: 28px;
    left: 0;
    font-size: 12px;
    color: #ff4949;
  }
}
</style>
